package cn.doctor.assistant.pad.ui;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.doctor.assistant.pad.MyApplication;
import cn.doctor.assistant.pad.R;
import cn.doctor.assistant.pad.api.AssistAPI;
import cn.doctor.assistant.pad.api.hudong.ChatApi;
import cn.doctor.assistant.pad.api.login.LoginApi;
import cn.doctor.assistant.pad.api.login.LoginResponse;
import cn.doctor.assistant.pad.base.BaseNetActivity;
import cn.doctor.assistant.pad.base.ResultCallback;
import cn.doctor.assistant.pad.db.AssistantPerferences;
import cn.doctor.assistant.pad.entity.GroupsBean;

/**
 * 登录
 */
public class LoginActivity extends BaseNetActivity {

    @InjectView(R.id.edit_phone)
    EditText editPhone;
    @InjectView(R.id.edit_password)
    EditText editPassword;
    @InjectView(R.id.login_button)
    Button loginButton;
    @InjectView(R.id.text_host_ip)
    TextView textHostIp;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.inject(this);

        String phone = AssistantPerferences.get(AssistantPerferences.KEY_LOGIN_PHONE, String.class);
        String psw = AssistantPerferences.get(AssistantPerferences.KEY_LOGIN_PASSWORD, String.class);
        if (phone != null) {
            editPhone.setText(phone);
        }
        if (psw != null) {
            editPassword.setText(psw);
        }

        editPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) {
                    onLogin();
                    return true;
                }
                return false;
            }
        });

        /*if (phone != null && psw != null) {
            onLogin();
        }*/
    }

    @OnClick(R.id.login_button)
    public void onLogin() {
        // test...
        //UI.startActivity(MainActivity.class);

        final String phone = editPhone.getText().toString();
        String password = editPassword.getText().toString();
        if (phone.isEmpty()) {
            showToast("请输入手机号");
            editPhone.requestFocus();
            return;
        }

        if (phone.length() < 11) {
            showToast("手机号长度不够");
            editPhone.requestFocus();
            return;
        }

        if (password.isEmpty()) {
            showToast("请输入密码");
            editPassword.requestFocus();
            return;
        }

        // 保存用户名密码
        AssistantPerferences.save(AssistantPerferences.KEY_LOGIN_PHONE, phone);
        AssistantPerferences.save(AssistantPerferences.KEY_LOGIN_PASSWORD, password);

        showProgress("登录中");

        LoginApi.login(phone, password, new ResultCallback<LoginResponse>() {
            @Override
            public void onSuccess(LoginResponse loginResponse) {
                onLoginSuccess(loginResponse, phone);
            }

            @Override
            public void onFail(String msg) {
                super.onFail(msg);
                stopProgress();
            }
        });


    }

    private void onLoginSuccess(LoginResponse loginResponse, String phone) {
        MyApplication.getInstance().setHxId(phone);
        // save
        MyApplication.getInstance().mAssistUser = loginResponse.getAssitant();
        if (loginResponse.getDoctor_array() != null) {
            if (loginResponse.getDoctor_array().size() == 0) {
                stopProgress();
                showToast("暂无此账号的相关医生！");
                return;
            }

            MyApplication.getInstance().mDoctors = loginResponse.getDoctor_array();
            MyApplication.getInstance().mCurrDoctor = MyApplication.getInstance().mDoctors.get(0);
        }

        // 加载联系人
        loadContacts();
    }

    private void loadContacts() {
        ChatApi.getContactGroupsByType(new ResultCallback<List<GroupsBean>>() {
            @Override
            public void onSuccess(List<GroupsBean> result) {
                stopProgress();
                UI.showToast("登录成功");
                MyApplication.getInstance().setGroups(result);
                UI.startActivity(MainActivity.class);
                LoginActivity.this.finish();
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        //取消网络请求
        //mRequestQueue.cancelAll(LoginApi.METHOD_LOGIN);
    }

    @OnClick(R.id.text_host_ip)
    public void onClick() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        String ip = AssistAPI.URL_DOMAIN;
        builder.setTitle("修改服务地址").setMessage("当前服务地址:" + ip);

        View view = UI.inflateView(R.layout.dialog_view_chat);
        builder.setView(view);
        final EditText editText = (EditText) view.findViewById(R.id.eidt_dialog_input);
        editText.setText(ip);
        builder.setPositiveButton("修改", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                AssistAPI.URL_DOMAIN = editText.getText().toString().trim();
                showToast("服务IP地址已修改");
            }
        }).setNegativeButton("取消", null).create().show();
    }
}

